package com.jcx.ldzj.service.impl;

import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson.JSONObject;
import com.jcx.ldzj.entity.*;
import com.jcx.ldzj.service.IBaseService;
import com.jcx.ldzj.utile.CacheServiceUtile;
import com.jcx.ldzj.utile.RedisUtil;
import com.jcx.ldzj.utile.StringUtile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheType;
import org.springframework.stereotype.Service;
import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.CentralProcessor.TickType;
import oshi.hardware.GlobalMemory;
import oshi.hardware.HardwareAbstractionLayer;
import oshi.software.os.FileSystem;
import oshi.software.os.OSFileStore;
import oshi.software.os.OperatingSystem;
import oshi.util.Util;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;

@Service
@Slf4j
public class BaseServiceIpm implements IBaseService {

    @Autowired
    private RedisUtil redisclient;
    @Autowired
    private CacheServiceUtile cacheServiceUtile;
    @Override
    public SystemHardwareInfo getSystem() {
        String s = redisclient.get("systemcache" + NetUtil.getLocalhostStr());
        if(StringUtile.isNotNull(s)){
            SystemHardwareInfo systemHardwareInfo = JSONObject.parseObject(s, SystemHardwareInfo.class);
            return systemHardwareInfo;
        }
        SystemHardwareInfo system = new SystemHardwareInfo();
        this.copyTo(system);
        system.setCache(getCacheInfo());

        redisclient.set("systemcache" + NetUtil.getLocalhostStr(),JSONObject.toJSONString(system));
        return system;
    }

    public void copyTo(SystemHardwareInfo system) {
        SystemInfo si = new SystemInfo();
        HardwareAbstractionLayer hal = si.getHardware();

        system.setCpu(getCpuInfo(hal.getProcessor()));

        system.setMem(getMemInfo(hal.getMemory()));

        system.setSys(getSysInfo());

        system.setJvm(getJvmInfo());

        system.setSysFiles(getSysFiles(si.getOperatingSystem()));
    }

    /**
     * 获取缓存信息
     * @return
     */
    public Cache getCacheInfo() {
        Map<Object, Object> info = cacheServiceUtile.getServerInfo();
        Cache cache = new Cache();
        cache.setType(CacheType.REDIS);
        cache.setOs(String.valueOf(info.get("os")));
        cache.setVersion(String.valueOf(info.get("redis_version")));
        cache.setPort(Integer.valueOf(info.get("tcp_port").toString()));
        cache.setUptimeInSeconds(Long.parseLong(info.get("uptime_in_seconds").toString()));
        cache.setConnectedClients(Integer.parseInt(info.get("connected_clients").toString()));
        cache.setUsed(Long.parseLong(info.get("used_memory").toString()));
        cache.setTotal(Long.parseLong(info.get("total_system_memory").toString()));
        cache.setDbSize(Long.parseLong(info.get("dbSize").toString()));
        cache.setUsedCpu(Double.parseDouble(info.get("used_cpu_user_children").toString()));
        cache.setMode(info.get("redis_mode").toString());
        cache.setIp(info.get("ip").toString());
        return cache;
    }

    /**
     * 设置CPU信息
     */
    private Cpu getCpuInfo(CentralProcessor processor ) {
        Cpu cpu=new Cpu();
        // CPU信息
        long[] prevTicks = processor.getSystemCpuLoadTicks();
        Util.sleep(SystemHardwareInfo.OSHI_WAIT_SECOND);
        long[] ticks = processor.getSystemCpuLoadTicks();
        long nice = ticks[TickType.NICE.getIndex()] - prevTicks[TickType.NICE.getIndex()];
        long irq = ticks[TickType.IRQ.getIndex()] - prevTicks[TickType.IRQ.getIndex()];
        long softirq = ticks[TickType.SOFTIRQ.getIndex()] - prevTicks[TickType.SOFTIRQ.getIndex()];
        long steal = ticks[TickType.STEAL.getIndex()] - prevTicks[TickType.STEAL.getIndex()];
        long cSys = ticks[TickType.SYSTEM.getIndex()] - prevTicks[TickType.SYSTEM.getIndex()];
        long user = ticks[TickType.USER.getIndex()] - prevTicks[TickType.USER.getIndex()];
        long iowait = ticks[TickType.IOWAIT.getIndex()] - prevTicks[TickType.IOWAIT.getIndex()];
        long idle = ticks[TickType.IDLE.getIndex()] - prevTicks[TickType.IDLE.getIndex()];
        long totalCpu = user + nice + cSys + idle + iowait + irq + softirq + steal;
        cpu.setCpuNum(processor.getLogicalProcessorCount());
        cpu.setTotal(totalCpu);
        cpu.setSys(cSys);
        cpu.setUsed(user);
        cpu.setWait(iowait);
        cpu.setFree(idle);
        return cpu;
    }

    /**
     * 设置内存信息
     */
    private Mem getMemInfo(GlobalMemory memory) {
        Mem mem = new Mem();
        mem.setTotal(memory.getTotal());
        mem.setUsed(memory.getTotal() - memory.getAvailable());
        mem.setFree(memory.getAvailable());
        return mem;
    }

    /**
     * 设置服务器信息
     */
    private Sys getSysInfo() {
        Sys sys = new Sys();
        Properties props = System.getProperties();
        try {
            sys.setComputerName(InetAddress.getLocalHost().getHostName());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        sys.setComputerIp(NetUtil.getLocalhostStr());
        sys.setOsName(props.getProperty("os.name"));
        sys.setOsArch(props.getProperty("os.arch"));
        sys.setUserDir(props.getProperty("user.dir"));
        return sys;
    }

    /**
     * 设置Java虚拟机
     */
    private Jvm getJvmInfo() {
        Jvm jvm = new Jvm();
        Properties props = System.getProperties();
        jvm.setTotal(Runtime.getRuntime().totalMemory());
        jvm.setMax(Runtime.getRuntime().maxMemory());
        jvm.setFree(Runtime.getRuntime().freeMemory());
        jvm.setVersion(props.getProperty("java.version"));
        jvm.setHome(props.getProperty("java.home"));
        return jvm;
    }

    /**
     * 设置磁盘信息
     */
    private List<SysFile> getSysFiles(OperatingSystem os) {
        List<SysFile> sysFiles = new LinkedList<SysFile>();
        FileSystem fileSystem = os.getFileSystem();
        OSFileStore[] fsArray = fileSystem.getFileStores();
        for (OSFileStore fs : fsArray) {
            long free = fs.getUsableSpace();
            long total = fs.getTotalSpace();
            long used = total - free;
            SysFile sysFile = new SysFile();
            sysFile.setDirName(fs.getMount());
            sysFile.setSysTypeName(fs.getType());
            sysFile.setTypeName(fs.getName());
            sysFile.setTotal(convertFileSize(total));
            sysFile.setFree(convertFileSize(free));
            sysFile.setUsed(convertFileSize(used));
            sysFile.setUsage(NumberUtil.round(NumberUtil.mul(used, total, 4), 100).doubleValue());
            sysFiles.add(sysFile);
        }
        return sysFiles;
    }

    /**
     * 字节转换
     *
     * @param size 字节大小
     * @return 转换后值
     */
    public String convertFileSize(long size) {
        long kb = 1024;
        long mb = kb * 1024;
        long gb = mb * 1024;
        if (size >= gb) {
            return String.format("%.1f GB" , (float) size / gb);
        } else if (size >= mb) {
            float f = (float) size / mb;
            return String.format(f > 100 ? "%.0f MB" : "%.1f MB" , f);
        } else if (size >= kb) {
            float f = (float) size / kb;
            return String.format(f > 100 ? "%.0f KB" : "%.1f KB" , f);
        } else {
            return String.format("%d B" , size);
        }
    }
}
